package com.dfrz.planeclub.controller;

import com.dfrz.planeclub.pojo.Admin;
import com.dfrz.planeclub.pojo.User;
import com.dfrz.planeclub.service.AdminService;
import com.dfrz.planeclub.service.UserService;
import com.dfrz.planeclub.utill.*;
//import kotlin.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author PuXiaLing
 * @description: TODO
 * @date 2024/4/10 17:23
 */
@RestController
@CrossOrigin(origins = "*")
public class UserController {

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    UserService userService;

    @Resource
    AdminService adminService;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    /**
     * 通过账号密码方式登录
     *
     * @param loginData 前端传入的登录角色（0：用户，1：教练2：调度员3管理员）/账号密码信息
     * @return 返回给前端token或者登录失败
     */
    @RequestMapping("/loginAcc")
    public BaseResult loginAcc(@RequestBody Map<String, Object> loginData) {
        System.out.println(loginData);
        BaseResult baseResult = null;
        if (Integer.parseInt(loginData.get("loginUse").toString()) != 3) {
            Admin adminer = new Admin();
            adminer.setAccount(loginData.get("account").toString());
            adminer.setPassword(loginData.get("password").toString());
            adminer.setType(Integer.parseInt(loginData.get("loginUse").toString()));
            Admin admin = adminService.accLogin(adminer);
            Map<String, Object> map = new HashMap<>();
            System.out.println(admin);
            if (admin != null) {
                //将账号密码存入uuid
                UUID uuid = UUID.randomUUID();
                String suuid = uuid.toString();
                redisTemplate.opsForValue().set(suuid, admin);
                map.put("mytoken", suuid);
                //返回token
                map.put("avatar", "");
                baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, map);
            } else {
                baseResult = BaseResult.setResult(ResultCodeEnum.FAILURE, null);
            }
        } else {
            User loginer = new User();
            loginer.setAccount(loginData.get("account").toString());
            loginer.setPassword(loginData.get("password").toString());
            User user = userService.accLogin(loginer);
            Map<String, Object> map = new HashMap<>();
            System.out.println(user);
            if (user != null) {
                //将账号密码存入uuid
                UUID uuid = UUID.randomUUID();
                String suuid = uuid.toString();
                redisTemplate.opsForValue().set(suuid, user);
                map.put("mytoken", suuid);
                map.put("avatar", user.getAvatar());
                //返回token
                baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, map);
            } else {
                baseResult = BaseResult.setResult(ResultCodeEnum.FAILURE, null);
            }
        }
        return baseResult;
    }

    /**
     * 检查用户手机是被已经注册，发送验证码并返回
     *
     * @param user1 用户手机号
     * @return 验证码
     */
    @RequestMapping("/getCode")
    public BaseResult getCode(@RequestBody User user1) throws Exception {
        System.out.println(user1);
        BaseResult baseResult = null;
        User user = userService.getPhone(user1.getPhone());
        if (user != null) {
            int code = MsgUtil.sendCode(user1.getPhone());
            Map<String, Object> map = new HashMap<>();
            map.put("code", code);
            //返回验证码
            baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, map);
        } else {
            baseResult = BaseResult.setResult(ResultCodeEnum.FAILURE, null);
        }
        return baseResult;
    }

    //    注册验证手机号并发送验证码
    @RequestMapping("/getCode2")
    public BaseResult getCode2(@RequestBody User user1) throws Exception {
        System.out.println(user1);
        BaseResult baseResult = null;
        User user = userService.getPhone(user1.getPhone());
        if (user == null) {
            int code = MsgUtil.sendCode(user1.getPhone());
            Map<String, Object> map = new HashMap<>();
            map.put("code", code);
            //返回验证码
            map.put("avatar", "");
            baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, map);
        } else {
            baseResult = BaseResult.setResult(ResultCodeEnum.FAILURE, null);
        }
        return baseResult;
    }

    /**
     * 手机登录
     *
     * @param user1 登录手机
     * @return token
     * @throws Exception
     */
    @RequestMapping("/loginPho")
    public BaseResult loginPho(@RequestBody User user1) throws Exception {
        System.out.println(user1);
        BaseResult baseResult = null;
        User user = userService.getPhone(user1.getPhone());
        if (user != null) {
            int code = MsgUtil.sendCode(user1.getPhone());
            Map<String, Object> map = new HashMap<>();
            UUID uuid = UUID.randomUUID();
            String suuid = uuid.toString();
            redisTemplate.opsForValue().set(suuid, user);
            map.put("mytoken", suuid);
            baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, map);
        } else {
            baseResult = BaseResult.setResult(ResultCodeEnum.FAILURE, null);
        }
        return baseResult;
    }

    /**
     * 注册时检验手机号、账号、用户名是否重复
     *
     * @param users
     * @return
     * @throws Exception
     */
    @RequestMapping("/check")
    public BaseResult check(@RequestBody User users) throws Exception {
        System.out.println(users);
        BaseResult baseResult = null;
        Map<String, Object> userMap = userService.check(users);
        baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, userMap);
        return baseResult;
    }

    /**
     * 注册，添加用户信息
     *
     * @param users 用户名，密码等
     * @return token
     * @throws Exception
     */
    @RequestMapping("/regist")
    public BaseResult regist(@RequestBody User users) throws Exception {
        System.out.println(users);
        BaseResult baseResult = null;
        User user = userService.regist(users);
        Map<String, Object> userMap = new HashMap<>();
        UUID uuid = UUID.randomUUID();
        String suuid = uuid.toString();
        redisTemplate.opsForValue().set(suuid, user);
        userMap.put("mytoken", suuid);
        userMap.put("avatar", user.getAvatar());
        baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, userMap);
        return baseResult;
    }

    /**
     * 检查登录状态
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkLoginer")
    public BaseResult checkLoginer(@RequestBody Map<String, Object> tokenMap) throws Exception {
        String token = (String) tokenMap.get("token");
        ;
        BaseResult baseResult = null;
        Map<String, Object> map = new HashMap<>();
        User user = (User) redisTemplate.opsForValue().get(token);
        String oldIdent = user.getIdNum();
        String hiddenIdent = "";
        if (oldIdent == null || oldIdent.length() < 18) {
            hiddenIdent = "";
            ; // 如果身份证号码为空或长度不足18位，直接返回原字符串
        } else {
            // 保留前6位和后4位，中间用星号(*)替换
            hiddenIdent = oldIdent.substring(0, 6) + "**********" + oldIdent.substring(oldIdent.length() - 4);
        }
        user.setIdNum(hiddenIdent);
        map.put("data", user);
        if (user != null) {
            baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, map);
        } else {
            baseResult = BaseResult.setResult(ResultCodeEnum.USER_NOLOGIN, null);
        }
        return baseResult;
    }

    /**
     * 用户退出，删除redis数据
     *
     * @param tokenMap
     * @return
     * @throws Exception
     */
    @RequestMapping("/exit")
    public BaseResult exit(@RequestBody Map<String, Object> tokenMap) throws Exception {
        System.out.println(tokenMap);
        BaseResult baseResult = null;
        boolean s = redisTemplate.delete((String) tokenMap.get("token"));
        System.out.println(s);
        baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, null);
        return baseResult;
    }

    /**
     * 用户头像上传到阿里云oss
     *
     * @param file  头像文件
     * @param token 用户信息
     * @return 新的头像信息
     * @throws IOException
     */
    @PostMapping("/changeAcatar")
    public BaseResult upload(@RequestParam("upfile") MultipartFile file,
                             @RequestParam("token") String token) throws IOException {
        User user = (User) redisTemplate.opsForValue().get(token);
        //调用阿里云OSS工具类进行文件上传
        System.out.println(token);
        Date now = new Date();
        String fileName = user.getName();
//        阿里云oss上传图片
        String url = aliOSSUtils.upload(file, fileName);
        user.setAvatar(url);
//        将oss文件名存到数据库中
        boolean sta = userService.update(user);
        BaseResult baseResult = null;
        if (sta) {
            boolean s = redisTemplate.delete(token);
            UUID uuid = UUID.randomUUID();
            String suuid = uuid.toString();
            redisTemplate.opsForValue().set(suuid, user);
            Map<String, Object> map = new HashMap<>();
            map.put("mytoken", suuid);
            map.put("url", url);
            baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, map);
        } else {
            baseResult = BaseResult.setResult(ResultCodeEnum.FAILURE, null);
        }
        return baseResult;
    }

    /**
     * 实名认证
     *
     * @param mapGet 获取的用户身份信息，包括真实姓名，身份证号码和token
     * @return
     * @throws Exception
     */
    @RequestMapping("/realName")
    public BaseResult realNmae(@RequestBody Map<String, Object> mapGet) throws Exception {
        System.out.println(mapGet);
        Map<String, Object> map = IdTestUtil.getIdentify((String) mapGet.get("realName"), (String) mapGet.get("idNum"));
        BaseResult baseResult = null;
        if (map.get("respMessage").equals("身份证信息匹配")) {
            User user = (User) redisTemplate.opsForValue().get(mapGet.get("token"));
            user.setIdNum((String) map.get("idNo"));
            user.setRealName((String) map.get("name"));
            user.setBirthDate((String) map.get("birthday"));
            user.setSex(map.get("sex").equals("M") ? 1 : 0);
            //更新数据库数据
            userService.update(user);
            Map<String, Object> sendMap = new HashMap<>();
            User infoUser = userService.accLogin(user);
            //更新token
            redisTemplate.opsForValue().set(mapGet.get("token"), user);
            sendMap.put("user", infoUser);
            baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, sendMap);
        } else {
            baseResult = BaseResult.setResult(ResultCodeEnum.FAILURE, null);
        }
        return baseResult;
    }

    /**
     * 更新用户名与住址
     * @param mapGet 用户名与住址
     * @return 更新后的user
     * @throws Exception
     */
    @RequestMapping("/updateBase")
    public BaseResult updateBase(@RequestBody Map<String, Object> mapGet) throws Exception {
        System.out.println(mapGet);
        User user = (User) redisTemplate.opsForValue().get(mapGet.get("token"));
        user.setName((String) mapGet.get("name"));
        user.setAddress((String) mapGet.get("address"));
        //更新数据库数据
        userService.update(user);
        Map<String, Object> sendMap = new HashMap<>();
        User infoUser = userService.accLogin(user);
        //更新token
        redisTemplate.opsForValue().set(mapGet.get("token"), user);
        sendMap.put("user", infoUser);
        BaseResult baseResult = null;
        baseResult = BaseResult.setResult(ResultCodeEnum.SUCCESS, sendMap);
        return baseResult;
    }
}